<template>
  <div class="retail-members">
    <div class="page-header">
      <h2>会员管理</h2>
      <p>管理零售会员信息，包括会员等级、积分、消费记录等</p>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="会员号">
          <el-input v-model="searchForm.memberNo" placeholder="请输入会员号" clearable />
        </el-form-item>
        <el-form-item label="会员姓名">
          <el-input v-model="searchForm.name" placeholder="请输入会员姓名" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="会员等级">
          <el-select v-model="searchForm.level" placeholder="请选择等级" clearable>
            <el-option label="普通会员" value="normal" />
            <el-option label="银卡会员" value="silver" />
            <el-option label="金卡会员" value="gold" />
            <el-option label="钻石会员" value="diamond" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="正常" value="active" />
            <el-option label="冻结" value="frozen" />
            <el-option label="注销" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="button-group">
      <el-button type="primary" @click="handleAdd" v-if="hasPermission('retail:member:add')">
        <el-icon><Plus /></el-icon>新增会员
      </el-button>
      <el-button type="success" @click="handleExport">导出</el-button>
      <el-button type="warning" @click="handleBatchUpdate">批量操作</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="card">
      <el-table 
        :data="tableData" 
        v-loading="loading" 
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="memberNo" label="会员号" width="120" />
        <el-table-column prop="name" label="会员姓名" width="100" />
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="level" label="会员等级" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelType(row.level)">
              {{ getLevelText(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="points" label="积分" width="80" />
        <el-table-column prop="totalAmount" label="累计消费" width="120">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastConsumeTime" label="最后消费" width="180" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="registerTime" label="注册时间" width="180" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="handleEdit(row)"
              v-if="hasPermission('retail:member:edit')"
            >
              编辑
            </el-button>
            <el-button 
              type="info" 
              size="small" 
              @click="handlePoints(row)"
            >
              积分
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              @click="handleRecords(row)"
            >
              记录
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
              v-if="hasPermission('retail:member:delete')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="会员姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入会员姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="会员等级" prop="level">
              <el-select v-model="form.level" placeholder="请选择等级" style="width: 100%">
                <el-option label="普通会员" value="normal" />
                <el-option label="银卡会员" value="silver" />
                <el-option label="金卡会员" value="gold" />
                <el-option label="钻石会员" value="diamond" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                v-model="form.birthday"
                type="date"
                placeholder="请选择生日"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="form.gender">
                <el-radio value="male">男</el-radio>
                <el-radio value="female">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio value="active">正常</el-radio>
                <el-radio value="frozen">冻结</el-radio>
                <el-radio value="cancelled">注销</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 权限检查
const hasPermission = (permission) => {
  return userStore.hasPermission(permission)
}

// 搜索表单
const searchForm = reactive({
  memberNo: '',
  name: '',
  phone: '',
  level: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  id: null,
  name: '',
  phone: '',
  level: 'normal',
  gender: 'male',
  birthday: '',
  address: '',
  status: 'active',
  remark: ''
})

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入会员姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  level: [{ required: true, message: '请选择会员等级', trigger: 'change' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 模拟数据
const mockData = [
  {
    id: 1,
    memberNo: 'M001',
    name: '张三',
    phone: '13800138001',
    level: 'gold',
    points: 2580,
    totalAmount: 12580.50,
    lastConsumeTime: '2024-01-15 14:30:00',
    status: 'active',
    gender: 'male',
    birthday: '1990-05-15',
    address: '北京市朝阳区建国路88号',
    remark: 'VIP客户',
    registerTime: '2023-01-15 10:30:00'
  },
  {
    id: 2,
    memberNo: 'M002',
    name: '李四',
    phone: '13800138002',
    level: 'silver',
    points: 1250,
    totalAmount: 6250.00,
    lastConsumeTime: '2024-01-14 16:20:00',
    status: 'active',
    gender: 'female',
    birthday: '1988-08-20',
    address: '上海市黄浦区南京东路123号',
    remark: '',
    registerTime: '2023-03-20 14:20:00'
  },
  {
    id: 3,
    memberNo: 'M003',
    name: '王五',
    phone: '13800138003',
    level: 'diamond',
    points: 5680,
    totalAmount: 28560.00,
    lastConsumeTime: '2024-01-13 11:15:00',
    status: 'active',
    gender: 'male',
    birthday: '1985-12-10',
    address: '广州市天河区天河路456号',
    remark: '钻石会员',
    registerTime: '2022-08-10 09:15:00'
  },
  {
    id: 4,
    memberNo: 'M004',
    name: '赵六',
    phone: '13800138004',
    level: 'normal',
    points: 320,
    totalAmount: 1600.00,
    lastConsumeTime: '2024-01-12 19:45:00',
    status: 'frozen',
    gender: 'female',
    birthday: '1992-03-25',
    address: '深圳市福田区华强北路789号',
    remark: '新会员',
    registerTime: '2023-12-01 16:45:00'
  },
  {
    id: 5,
    memberNo: 'M005',
    name: '钱七',
    phone: '13800138005',
    level: 'gold',
    points: 1890,
    totalAmount: 9450.00,
    lastConsumeTime: '2024-01-11 13:30:00',
    status: 'active',
    gender: 'male',
    birthday: '1987-07-08',
    address: '杭州市西湖区湖滨路321号',
    remark: '',
    registerTime: '2023-05-15 11:20:00'
  },
  {
    id: 6,
    memberNo: 'M006',
    name: '孙八',
    phone: '13800138006',
    level: 'silver',
    points: 980,
    totalAmount: 4900.00,
    lastConsumeTime: '2024-01-10 15:15:00',
    status: 'cancelled',
    gender: 'female',
    birthday: '1995-11-18',
    address: '成都市锦江区春熙路654号',
    remark: '已注销',
    registerTime: '2023-07-22 09:30:00'
  },
  {
    id: 7,
    memberNo: 'M007',
    name: '周九',
    phone: '13800138007',
    level: 'normal',
    points: 150,
    totalAmount: 750.00,
    lastConsumeTime: '2024-01-09 17:00:00',
    status: 'active',
    gender: 'male',
    birthday: '1993-09-12',
    address: '武汉市江汉区江汉路987号',
    remark: '',
    registerTime: '2023-11-05 14:15:00'
  },
  {
    id: 8,
    memberNo: 'M008',
    name: '吴十',
    phone: '13800138008',
    level: 'gold',
    points: 2100,
    totalAmount: 10500.00,
    lastConsumeTime: '2024-01-08 12:30:00',
    status: 'active',
    gender: 'female',
    birthday: '1989-04-30',
    address: '西安市碑林区钟楼南路147号',
    remark: '忠实客户',
    registerTime: '2023-02-14 10:45:00'
  }
]

// 获取等级样式
const getLevelType = (level) => {
  const typeMap = {
    normal: 'info',
    silver: 'warning',
    gold: 'success',
    diamond: 'danger'
  }
  return typeMap[level] || 'info'
}

// 获取等级文本
const getLevelText = (level) => {
  const textMap = {
    normal: '普通会员',
    silver: '银卡会员',
    gold: '金卡会员',
    diamond: '钻石会员'
  }
  return textMap[level] || '未知'
}

// 获取状态样式
const getStatusType = (status) => {
  const statusMap = {
    active: 'success',
    frozen: 'warning',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    active: '正常',
    frozen: '冻结',
    cancelled: '注销'
  }
  return textMap[status] || '未知'
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    memberNo: '',
    name: '',
    phone: '',
    level: '',
    status: ''
  })
  handleSearch()
}

// 加载数据
const loadData = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    tableData.value = mockData
    pagination.total = mockData.length
    loading.value = false
  }, 500)
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增会员'
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑会员'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  ElMessage.info(`查看会员详情：${row.name}`)
}

// 积分管理
const handlePoints = (row) => {
  ElMessage.info(`积分管理功能开发中... 会员：${row.name}`)
}

// 消费记录
const handleRecords = (row) => {
  ElMessage.info(`消费记录功能开发中... 会员：${row.name}`)
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个会员吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟删除
    ElMessage.success('删除成功')
    loadData()
  } catch {
    // 用户取消
  }
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 批量操作
const handleBatchUpdate = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要操作的会员')
    return
  }
  ElMessage.info('批量操作功能开发中...')
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟提交
    setTimeout(() => {
      ElMessage.success(form.id ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadData()
      submitLoading.value = false
    }, 1000)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    name: '',
    phone: '',
    level: 'normal',
    gender: 'male',
    birthday: '',
    address: '',
    status: 'active',
    remark: ''
  })
}

// 对话框关闭
const handleDialogClose = () => {
  resetForm()
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.retail-members {
  .page-header {
    margin-bottom: 20px;
    
    h2 {
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
      color: $text-color-primary;
    }
    
    p {
      margin: 0;
      color: $text-color-regular;
      font-size: 14px;
    }
  }
  
  .search-form {
    background: white;
    padding: 20px;
    border-radius: $border-radius-base;
    box-shadow: $box-shadow-light;
    margin-bottom: 20px;
  }
  
  .button-group {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
  }
  
  .card {
    background: white;
    border-radius: $border-radius-base;
    box-shadow: $box-shadow-light;
    padding: 20px;
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 